const state = {
	visitedViews: []
};

const mutations = {
	// 添加tab
	ADD_VISITED_VIEW: (state, view) => {
		// 首次访问必须先初始化首页
		if (!state.visitedViews.length) {
			state.visitedViews.push({ path: "/dashboard", title: "首页" });
		}
		// 判断是否已添加
		if (state.visitedViews.some(v => v.path === view.path)) return;
		state.visitedViews.push(view);
	},
	// 删除tab
	DEL_VISITED_VIEW: (state, view) => {
		let indexValue = state.visitedViews.findIndex(item => item.path === view.path);
		state.visitedViews.splice(indexValue, 1);
	},
	// 删除其他tag
	DEL_OTHERS_VISITED_VIEWS: (state, view) => {
		state.visitedViews = state.visitedViews.filter(v => {
			return v.meta.affix || v.path === view.path;
		});
	},
	// 删除所有tag
	DEL_ALL_VISITED_VIEWS: state => {
		state.visitedViews = [];
	},
	// 更新tag
	UPDATE_VISITED_VIEW: (state, view) => {
		for (let v of state.visitedViews) {
			if (v.path === view.path) {
				v = Object.assign(v, view);
				break;
			}
		}
	}
};

const actions = {
	addVisitedView({ commit }, view) {
		commit("ADD_VISITED_VIEW", view);
	},

	delVisitedView({ commit, state }, view) {
		return new Promise(resolve => {
			commit("DEL_VISITED_VIEW", view);
			resolve([...state.visitedViews]);
		});
	},

	delOthersVisitedViews({ commit, state }, view) {
		return new Promise(resolve => {
			commit("DEL_OTHERS_VISITED_VIEWS", view);
			resolve([...state.visitedViews]);
		});
	},

	delAllVisitedViews({ commit, state }) {
		return new Promise(resolve => {
			commit("DEL_ALL_VISITED_VIEWS");
			resolve([...state.visitedViews]);
		});
	},
	updateVisitedView({ commit }, view) {
		commit("UPDATE_VISITED_VIEW", view);
	}
};

export default {
	namespaced: true,
	state,
	mutations,
	actions
};
